const Koa = require("koa");
const path = require("path");
const koaBody = require("koa-body");
const koaParams = require("koa-parameter");
const jerror = require("koa-json-error");
const mongoose = require("mongoose");
const routing = require("./routes");
const cors = require("koa2-cors");
require("dotenv").config();

let options = {
  useNewUrlParser: true,
  useFindAndModify: false,
  useCreateIndex: true,
  autoIndex: false
};

mongoose.connect(process.env.MONGO_URL, options);
mongoose.connection
  .on("open", () => {
    console.log("MongoDB Connected!");
  })
  .on("error", console.error);

const app = new Koa();
app.use(cors());
app.use(async (ctx, next) => {
  await next();
  ctx.set("X-Content-Type-Options", "nosniff");
  ctx.response.set("Content-Type", "application/json");
});
app.use(
  jerror({
    postFormat: (err, { stack, ...rest }) =>
      process.env.NODE_ENV === "production" ? rest : { stack, ...rest }
  })
);

app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, "/public/uploads")
    }
  })
);
app.use(koaParams(app));
routing(app);
app.listen(3001);
